import redis
import random
import threading
import logging

from tlv import tlv_builder_hw
from tlv import tlv_builder_ab
from utils import util_socket

r = redis.Redis(host="139.224.70.66", port=6379, password="SSDEFE#@^&&N89Enet@#DW#S")
username = "qcp"
password = "123456"

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(thread)d %(threadName)s %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S', filename='log/logout.log')


class SendThread(threading.Thread):
    def __init__(self, data, service_info, sn, id, user_ip):
        threading.Thread.__init__(self)
        self.data = data
        self.service_info = service_info
        self.id = id
        self.sn = sn
        self.user_ip = user_ip

    def run(self):
        self.send()

    def send(self):
        logging.debug(self.data)
        logging.info("send a logout package to host {0};user_ip:{1}".format(self.service_info["ip"], self.user_ip))
        sender = util_socket.SocketUtils()
        result = sender.socket_client(self.service_info, self.data)
        logging.info("result value:{0}".format(result))
        r.hset("{sn}_result".format(sn=self.sn), self.id, result)


def byte_to_dict(data):
    data_arr = str(data, encoding="utf-8").split("&")
    data_dict = {}
    for i in data_arr:
        data_simple_arr = i.split("=")
        data_dict[data_simple_arr[0]] = data_simple_arr[1]
    return data_dict


def postpackage(data_list):
    for data in data_list:
        logout(byte_to_dict(data))


# def logout(ac_type, user_ip, user_mac,ac_ip, ac_port=2000):
def logout(data):
    id = data["id"]
    ac_type = data["ac_type"]
    ac_ip = data["ac_ip"]
    ac_port = data["ac_port"]
    user_ip = data["user_ip"]
    user_mac = data["user_mac"]
    ac_sn = data["ac_sn"]
    tb = ""
    if ac_type == "0":
        # 西加云杉
        send_data = {"type": 5, "serial_no": random.randint(0, 65535), "user_ip": user_ip,
                     "attr": {"username": username, "password": password}, "secret": "123456789"}
        tb = tlv_builder_hw.TlvBuilderHw(send_data)
    elif ac_type == "1":
        # 韵盛发
        send_data = {"type": 5, "serial_no": random.randint(0, 65535), "user_ip": user_ip,
                     "attr": {"abmac": user_mac}}
        tb = tlv_builder_ab.TlvBuilderAb(send_data)
    s_info = {"ip": ac_ip, "port": int(ac_port)}
    send_thread = SendThread(tb.build_data(), s_info, ac_sn, id, user_ip)
    send_thread.start()


# while (True):
#     school_list = ["school_1_logout", "school_2_logout", "school_3_logout", "school_4_logout"]
#     for i in school_list:
#         list_len = r.llen(i)
#         datalist = r.lrange(i, 0, list_len)
#         postpackage(datalist)
#         r.ltrim(i, list_len, -1)

data = {"id":"12345","ac_type":"0","ac_ip":"192.168.1.199","ac_port":"2000","user_ip":"192.168.1.187","user_mac":"12313","ac_sn":"11111111"}
logout(data)